﻿using CAP.Model;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MySqlConnector;
using System;

namespace CAP.Demo1.Controllers
{
    public class ProductController : Controller
    {
        private IOptions<AppSettings> _appSettings;

        public ProductController(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings;
        }

        [NonAction]
        [CapSubscribe("order.create")]
        public UpdateOrderStatus Update(UpdateProductStock model)
        {
            using (var connection = new MySqlConnection(_appSettings.Value.MySql))
            {
                //业务代码
                if (model.Count > 10) return new UpdateOrderStatus(model.OrderID, false);
                connection.Open();
                var cmd = connection.CreateCommand();
                cmd.CommandText = $"update tb_product set count=count-1 where id='{model.ProductID}'";
                cmd.ExecuteNonQuery();
                Console.WriteLine($"update stock id={model.ProductID} count={model.Count}");
                return new UpdateOrderStatus(model.OrderID, true);
            }
        }
    }
}